class ReportJob < ApplicationJob
  queue_as :default

  def perform(usage, name, *filter)
    file_path = "#{Rails.public_path}/报表/#{usage}/#{name}.xls"
    Report.create(usage: usage, name: name, path: file_path)
    case usage
    when '订单'
      columns = [
          :id, :order_no, 'members.name as member_name', 'members.mobile as member_mobile',
          "CASE
             WHEN appointments.course_en_name=appointments.course_cn_name then appointments.course_cn_name
             ELSE CONCAT(appointments.course_en_name, '|', appointments.course_cn_name)
           END as course_name",
          :total, :coupon, :promotion, :promotion_info, :experience_id, :experience_info,
          'COALESCE(transactions.price,0) as pay_amount', :pay_type, :status, :created_at, 'transactions.created_at as paid_at'
      ]
      book = Spreadsheet::Workbook.new
      sheet = book.create_worksheet(name: name)
      sheet.row(0).concat(%w{订单编号 会员 会员手机 课程 订单金额 优惠券抵用 活动优惠 活动信息　体验信息 实付金额 付款方式 下单时间 付款时间 订单状态})
      Order.joins(:member, :appointment).left_joins(:running_account).where(filter).select(columns).find_each do |order|
        sheet.row(sheet.row_count).concat(
            order.slice(:order_no, :member_name, :member_mobile, :course_name, :total, :coupon, :promotion, :promotion_info_detail, :experience_info_detail, :pay_amount, :pay_type, :created_at, :paid_at, :status_i18n).values
        )
      end
      logger.info "执行完毕"
      book.write file_path
    when '预约'
      columns = [
          :id, :timetable_id, "courses.id as course_id", "CONCAT(courses.en_name,'|',courses.name) as course_name",
          "CASE WHEN courses.usage = 0 THEN '免费课' ELSE '收费课' END as usage", 'member_card_id != 0 as is_member',
          'members.name as member_name', 'members.mobile as member_mobile', 'orders.order_no', 'orders.pay_type',
          'appointments.class_start_time', 'coaches.name as coach_name', 'companies.name as company_name',
          'stores.name as store_name', :quantity, :status, "orders.source as source", :created_at
      ]
      book = Spreadsheet::Workbook.new
      sheet = book.create_worksheet(name: name)
      sheet.row(0).concat(%w{课表编号 课程编号 课程名 课程类型 订单号 名额 课程时间 教练 集团 门店 状态 会员 会员名 会员手机号 来源 预约时间})
      Appointment.joins(:course, :coach, :member, :order, :company, :store).where(filter).select(columns).find_each do |appointment|
        sheet.row(sheet.row_count).concat(
            appointment.slice(:timetable_id, :course_id, :course_name, :usage, :order_no, :quantity, :class_start_time, :coach_name, :company_name, :store_name, :status_i18n, :is_member, :member_name, :member_mobile, :source, :created_at).values
        )
      end
      logger.info "执行完毕"
      book.write file_path
    else
      #nothing to do
    end
  end
end
